package org.apache.commons.graph.model

import com.gitee.wsl.text.format.format
import org.apache.commons.graph.Graph
import org.apache.commons.graph.GraphException
import org.apache.commons.graph.VertexPair
import org.apache.commons.graph.bean.DefaultEdge
import org.apache.commons.graph.utils.Objects
import kotlin.jvm.JvmField
import kotlin.jvm.JvmStatic


/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

typealias BaseSampleGraph<V> = BaseGraph<V, DefaultEdge<V>>

/**
 * Basic abstract in-memory based of a simple read-only [Graph] implementation. Subclasses may load adjacency
 * list/edges set in the constructor, or expose [org.apache.commons.graph.MutableGraph] APIs.
 *
 * This class is NOT thread safe!
 *
 * @param <V> the Graph vertices type
 * @param <E> the Graph edges type
</E></V> */
abstract class BaseGraph<V, E> : Graph<V, E> {
    /**
     * Returns the adjacency list where stored vertex/edges.
     *
     * @return the adjacency list where stored vertex/edges.
     */
    @JvmField
    protected val adjacencyList: MutableMap<V, MutableSet<V>> = HashMap()

    /**
     * Return the edge [Set]
     * @return the edge [Set]
     */
    @JvmField
    protected val allEdges: MutableSet<E> = HashSet()

    /**
     * Returns the `Map` of indexed edges.
     *
     * @return the [Map] of indexed edges
     */
    @JvmField
    protected val indexedEdges: MutableMap<VertexPair<V>, E> = HashMap()

    /**
     * Returns the `Map` of indexed vertices.
     *
     * @return the indexed vertices [Map]
     */
    @JvmField
    protected val indexedVertices: MutableMap<E, VertexPair<V>> = HashMap()

    /**
     * {@inheritDoc}
     */
    override fun containsEdge(e: E): Boolean {
        return indexedVertices.containsKey(e)
    }

    /**
     * {@inheritDoc}
     */
    override fun containsVertex(v: V): Boolean {
        return adjacencyList.containsKey(v)
    }

    /**
     * {@inheritDoc}
     */
    override fun equals(other: Any?): Boolean {
        if (this === other) {
            return true
        }

        if (other == null || this::class != other::class) {
            return false
        }

        other as BaseGraph<*, *>
        return adjacencyList == other.adjacencyList
    }

    /**
     * {@inheritDoc}
     */
    override fun getConnectedVertices(v: V): Iterable<V> {
        checkGraphCondition(containsVertex(v), "Vertex %s does not exist in the Graph", v)
        return adjacencyList[v]?: emptyList()
    }

    /**
     * {@inheritDoc}
     */
    override fun getEdge(source: V, target: V): E? {
        checkGraphCondition(containsVertex(source), "Vertex %s does not exist in the Graph", source)
        checkGraphCondition(containsVertex(target), "Vertex %s does not exist in the Graph", target)

        return indexedEdges[VertexPair(source, target)]
    }

    override val edges: Iterable<E>
        get() = allEdges

    override val order: Int
        get() = adjacencyList.size

    override val size: Int
        get() = allEdges.size


    override val vertices: Iterable<V>
        get() = adjacencyList.keys


    override fun getVertices(e: E): VertexPair<V>? {
        return indexedVertices[e]
    }

    /**
     * {@inheritDoc}
     */
    override fun hashCode(): Int {
        val prime = 31
        return Objects.hash(1, prime, adjacencyList, allEdges, indexedEdges, indexedVertices)
    }

    /**
     * {@inheritDoc}
     */
    override fun toString(): String {
        return adjacencyList.toString()
    }

    companion object {

        /**
         * Ensures the truth of an expression involving one or more parameters to the
         * calling method.
         *
         * @param expression a boolean expression
         * @param errorMessageTemplate a template for the exception message should the
         * check fail. The message is formed by replacing each `%s`
         * placeholder in the template with an argument. These are matched by
         * position - the first `%s` gets `errorMessageArgs[0]`, etc.
         * Unmatched arguments will be appended to the formatted message in square
         * braces. Unmatched placeholders will be left as-is.
         * @param errorMessageArgs the arguments to be substituted into the message
         * template. Arguments are converted to strings using
         * [String.valueOf].
         * @throws GraphException if `expression` is false
         */
        @JvmStatic
        protected fun checkGraphCondition(
            expression: Boolean,
            errorMessageTemplate: String,
            vararg errorMessageArgs: Any?
        ) {
            if (!expression) {
                throw GraphException(String.format(errorMessageTemplate, *errorMessageArgs))
            }
        }
    }
}
